package com.ruoyi.reception;

import com.google.gson.Gson;
import com.ruoyi.common.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @Description
 * @Author chenjian
 * @Date 2019/9/28 10:38
 * @Version V1.0
 **/
@Controller
@RequestMapping("/reception/weixin")
public class WeiXinOauthController {

    @Value("${weixin.appId}")
    public String appId;

    @Value("${weixin.appsecret}")
    public String appsecret;

    @Value("${weixin.redirectUri}")
    public String redirectUri;

    /**
     * 用户同意授权,获取code
     */
    @RequestMapping("/oauth")
    public void oauth(HttpServletResponse response) throws Exception {

        //scope:snsapi_userinfo 需要同意授权，snsapi_base 不需要同意授权
        String url="https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" +appId+
                "&redirect_uri=" + URLEncoder.encode(redirectUri,"UTF-8") +
                "&response_type=code" +
                "&scope=snsapi_base" +
                "&state=sdkjwxtest" +
                "#wechat_redirect";
        response.sendRedirect(url);

    }

    /**
     * 同意授权后的回调地址
     */
    @RequestMapping("/invoke")
    public String  ServerResponse(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String code=request.getParameter("code");
        String state=request.getParameter("state");

        //获取access_token
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" +appId+
                "&secret=" +appsecret+
                "&code=" +code+
                "&grant_type=authorization_code";

        String accessInfo = HttpClientUtils.get(url);

        Gson gson = new Gson();
        //获取返回的userInfo信息
        HashMap<String, String> accessInfoMap = gson.fromJson(accessInfo, HashMap.class);

        String access_token=accessInfoMap.get("access_token");
        String openid=accessInfoMap.get("openid");
        System.out.println("openid==>"+openid);
        return "redirect:http://www.baidu.com";
    }

}
